package org.kust.bbs.admin.service.impl;

import org.kust.bbs.admin.mapper.AdminMapper;
import org.kust.bbs.admin.service.IAdminService;
import org.kust.bbs.common.ex.ServiceException;
import org.kust.bbs.common.utils.JwtUtils;
import org.kust.bbs.common.utils.MD5Utils;
import org.kust.bbs.common.web.State;
import org.kust.bbs.pojo.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 管理员登录
     *
     * @param admin
     * @return
     */
    @Override
    public String login(Admin admin) {
        Admin adminInfo;
        String name = admin.getName();
        String password = admin.getPassword();

        if (name == null || password == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "名字和密码都不能为空");
        }
        adminInfo = adminMapper.selectAdmin(name);
        if (adminInfo == null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "没有该管理员账户");
        }
        if (!MD5Utils.MD5(password).equals(adminInfo.getPassword())) {
            throw new ServiceException(State.ERR_NOT_FOUND, "密码错误");
        }
        adminMapper.updateLsatLogin(LocalDateTime.now(), name);

        String jwtToken = JwtUtils.getJwtToken(adminInfo.getId(), name);
        return jwtToken;
    }

    /**
     * 查询管理员信息
     *
     * @param name
     * @return
     */
    @Override
    public Admin selectAdmin(String name) {
        Admin admin = adminMapper.selectAdmin(name);
        return admin;
    }
}